package zjc.bookkeeping.service.imp;

import android.util.Log;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import zjc.bookkeeping.db.ConsumptionBean;
import zjc.bookkeeping.db.DBManager;
import zjc.bookkeeping.minepage.dDatamanagement.DatamanagementMainActivity;
import zjc.bookkeeping.model.Account;
import zjc.bookkeeping.model.Consumption;
import zjc.bookkeeping.server.MyHttpUtil;
import zjc.bookkeeping.service.ConsumptionService;

public class ConsumptionServiceImp implements ConsumptionService {
    @Override
    public int addConsumption(String json, int userId,ConsumptionBean consumptionBean){
        final int[] consumptionId = {0};
        String url = MyHttpUtil.host +"/consumption/addConsumption";
        url += "?userId=" + userId;
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),json);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        OkHttpClient client=new OkHttpClient();
        Thread addThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseData);
                    int key = jsonObject.optInt("data",0);
//                    Log.i("---key",key+"--------");
                    consumptionBean.setConsumption_key(key);
                    DBManager.setConsumptionKey(consumptionBean);
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        addThread.start();
//        MyHttpUtil.sendOkhttpPostRequest(url, requestBody, new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.i("zjc",e.getMessage());
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String responseData = response.body().string();
//                Log.i("responseData",responseData);
//                try {
//                    JSONObject jsonObject = new JSONObject(responseData);
//                    int age = jsonObject.optInt("data",0);
//                    consumptionId[0] = age;
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
        return consumptionId[0];
    }

    @Override
    public boolean deleteConsumption(String accountId, int userId) {
        final boolean[] flag = {false};
        String url = MyHttpUtil.host + "/consumption/deleteConsumptionByAccountId";
        FormBody.Builder params = new FormBody.Builder();
        params.add("accountId",accountId);
        params.add("userId", String.valueOf(userId));
        Request request = new Request.Builder()
                .url(url)
                .post(params.build())
                .build();
        OkHttpClient client=new OkHttpClient();
        Thread addThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseData);
                    String data = jsonObject.optString("data",null);
                    if (data.equals("success")){
                        flag[0] = true;
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        addThread.start();
        return flag[0];
    }

    @Override
    public List<Consumption> findAllConsumption(int userId) {
        List<Consumption> consumptionList = new ArrayList<>();
        String url = MyHttpUtil.host + "/consumption/findAllConsumption";
        FormBody.Builder params = new FormBody.Builder();
        params.add("userId", String.valueOf(userId));
        Request request = new Request.Builder()
                .url(url)
                .post(params.build())
                .build();
        OkHttpClient client=new OkHttpClient();
        Thread addThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseData);
                    String data = jsonObject.optString("data",null);
                    if (!data.isEmpty()){
                        Log.i("data",data);
                        JSONArray array = new JSONArray(data);
                        for(int i = 0; i <array.length(); i++){
                            JSONObject object = array.getJSONObject(i);
                            Log.i("object", String.valueOf(object));
                            Consumption consumption = new Gson().fromJson(String.valueOf(object),Consumption.class);
                            ConsumptionBean consumptionBean = new ConsumptionBean();
                            consumptionBean.setConsumption_class_name(consumption.getConsumptionClassName());
                            consumptionBean.setConsumption_remarks(consumption.getConsumptionRemarks());
                            consumptionBean.setConsumption_money(consumption.getConsumptionMoney().floatValue());
                            consumptionBean.setConsumption_business(consumption.getConsumptionBusiness());
                            consumptionBean.setaccount_id(DBManager.getAccountId(consumption.getAccountUid()));
                            consumptionBean.setConsumption_method(consumption.getConsumptionMethod());
                            Date date = null;
                            try {
                                date = new SimpleDateFormat("yyyy年MM月dd日 HH:mm").parse(consumption.getConsumptionTime());
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            SimpleDateFormat timeS = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
                            String time = timeS.format(date);
                            SimpleDateFormat yearS = new SimpleDateFormat("yyyy");
                            String yearStr = yearS.format(date);
                            int year = Integer.parseInt(yearStr);
                            SimpleDateFormat monthS = new SimpleDateFormat("MM");
                            String monthStr = monthS.format(date);
                            int month = Integer.parseInt(monthStr);
                            SimpleDateFormat dayS = new SimpleDateFormat("dd");
                            String dayStr = dayS.format(date);
                            int day = Integer.parseInt(dayStr);
                            consumptionBean.setConsumption_time(time);
                            consumptionBean.setConsumption_year(year);
                            consumptionBean.setConsumption_month(month);
                            consumptionBean.setConsumption_day(day);
                            consumptionBean.setConsumption_kind(consumption.getConsumptionKind());
                            consumptionBean.setConsumption_key(consumption.getConsumptionId());
                            DBManager.insertConsumption(consumptionBean);
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        addThread.start();
        return consumptionList;
    }
}
